package com.core.cloudbusiness.system.demo.controller;

import com.core.cloudcommon.CommonResult;
import com.core.cloudcommon.utils.IdUtils;
import com.core.cloudcommon.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author =====Lqj=====
 * @className SnowflakeIdDemoController
 * @description 雪花ID生成器演示控制器
 * @create 2024/12/17 10:30
 **/
@Slf4j
@RestController
@RequestMapping("/api/demo/snowflake")
public class SnowflakeIdDemoController {

    /**
     * 生成系统用户ID
     */
    @GetMapping("/user-id")
    public CommonResult<Map<String, Object>> generateUserId() {
        long id = IdUtils.generateSystemUserId();
        SnowflakeIdGenerator.SnowflakeInfo info = IdUtils.parseSnowflakeId(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("module", info.getModuleCode().getDescription());
        result.put("timestamp", info.getTimestamp());
        result.put("workerId", info.getWorkerId());
        result.put("sequence", info.getSequence());
        
        return CommonResult.OK(result);
    }

    /**
     * 生成工单ID
     * @param sheetType 工单类型：1001-12345工单，2001-网络工单，3001-信访工单
     */
    @GetMapping("/sheet-id")
    public CommonResult<Map<String, Object>> generateSheetId(
            @RequestParam(defaultValue = "1001") Integer sheetType) {
        
        long id = IdUtils.generateSheetId(sheetType);
        SnowflakeIdGenerator.SnowflakeInfo info = IdUtils.parseSnowflakeId(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("sheetType", sheetType);
        result.put("module", info.getModuleCode().getDescription());
        result.put("timestamp", info.getTimestamp());
        result.put("workerId", info.getWorkerId());
        result.put("sequence", info.getSequence());
        
        return CommonResult.OK(result);
    }

    /**
     * 批量生成ID
     * @param count 生成数量
     * @param moduleType 模块类型
     */
    @GetMapping("/batch-ids")
    public CommonResult<Map<String, Object>> generateBatchIds(
            @RequestParam(defaultValue = "10") Integer count,
            @RequestParam(defaultValue = "SYSTEM_USER") String moduleType) {
        
        SnowflakeIdGenerator.ModuleCode moduleCode;
        try {
            moduleCode = SnowflakeIdGenerator.ModuleCode.valueOf(moduleType);
        } catch (IllegalArgumentException e) {
            moduleCode = SnowflakeIdGenerator.ModuleCode.SYSTEM_USER;
        }
        
        long[] ids = IdUtils.generateIds(moduleCode, count);
        
        Map<String, Object> result = new HashMap<>();
        result.put("count", count);
        result.put("module", moduleCode.getDescription());
        result.put("ids", ids);
        
        return CommonResult.OK(result);
    }

    /**
     * 解析雪花ID
     * @param id 要解析的雪花ID
     */
    @GetMapping("/parse-id")
    public CommonResult<Map<String, Object>> parseId(@RequestParam Long id) {
        
        try {
            SnowflakeIdGenerator.SnowflakeInfo info = IdUtils.parseSnowflakeId(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("timestamp", info.getTimestamp());
            result.put("datacenterId", info.getDatacenterId());
            result.put("workerId", info.getWorkerId());
            result.put("sequence", info.getSequence());
            result.put("moduleCode", info.getModuleCode());
            result.put("moduleDescription", info.getModuleCode() != null ? info.getModuleCode().getDescription() : "未知模块");
            result.put("isValid", IdUtils.isValidSnowflakeId(id));
            
            return CommonResult.OK(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("error", e.getMessage());
            result.put("isValid", false);
            
            return CommonResult.OK(result);
        }
    }

    /**
     * 验证ID模块
     * @param id 要验证的雪花ID
     * @param expectedModule 期望的模块类型
     */
    @GetMapping("/validate-module")
    public CommonResult<Map<String, Object>> validateModule(
            @RequestParam Long id,
            @RequestParam String expectedModule) {
        
        try {
            SnowflakeIdGenerator.ModuleCode expectedModuleCode = SnowflakeIdGenerator.ModuleCode.valueOf(expectedModule);
            boolean isValidModule = IdUtils.isModuleId(id, expectedModuleCode);
            SnowflakeIdGenerator.ModuleCode actualModule = IdUtils.getIdModule(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("expectedModule", expectedModuleCode.getDescription());
            result.put("actualModule", actualModule != null ? actualModule.getDescription() : "未知模块");
            result.put("isValidModule", isValidModule);
            result.put("isValidId", IdUtils.isValidSnowflakeId(id));
            
            return CommonResult.OK(result);
        } catch (IllegalArgumentException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("error", "无效的模块类型: " + expectedModule);
            
            return CommonResult.OK(result);
        }
    }

    /**
     * 获取模块统计信息
     */
    @GetMapping("/statistics")
    public CommonResult<Map<String, Object>> getStatistics() {
        String statistics = IdUtils.getModuleStatistics();
        
        Map<String, Object> result = new HashMap<>();
        result.put("statistics", statistics);
        result.put("availableModules", SnowflakeIdGenerator.ModuleCode.values());
        
        return CommonResult.OK(result);
    }

    /**
     * 性能测试
     * @param testCount 测试数量
     */
    @GetMapping("/performance-test")
    public CommonResult<Map<String, Object>> performanceTest(
            @RequestParam(defaultValue = "10000") Integer testCount) {
        
        long startTime = System.currentTimeMillis();
        
        for (int i = 0; i < testCount; i++) {
            IdUtils.generateSystemUserId();
        }
        
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        double idsPerSecond = (double) testCount / duration * 1000;
        
        Map<String, Object> result = new HashMap<>();
        result.put("testCount", testCount);
        result.put("duration", duration + " ms");
        result.put("idsPerSecond", String.format("%.2f", idsPerSecond));
        result.put("avgTimePerIdNs", duration * 1000000.0 / testCount);
        
        return CommonResult.OK(result);
    }

    /**
     * 生成所有模块的示例ID
     */
    @GetMapping("/all-modules")
    public CommonResult<Map<String, Object>> generateAllModulesIds() {
        Map<String, Object> result = new HashMap<>();
        
        // 系统模块
        Map<String, Object> systemModules = new HashMap<>();
        systemModules.put("用户模块", IdUtils.generateSystemUserId());
        systemModules.put("部门模块", IdUtils.generateSystemDepartId());
        systemModules.put("登录模块", IdUtils.generateSystemLoginId());
        systemModules.put("日志模块", IdUtils.generateSystemLogId());
        systemModules.put("设备模块", IdUtils.generateSystemDeviceId());
        systemModules.put("安全模块", IdUtils.generateSystemSecurityId());
        
        // 工单模块
        Map<String, Object> sheetModules = new HashMap<>();
        sheetModules.put("12345工单", IdUtils.generateSheetMayorId());
        sheetModules.put("网络工单", IdUtils.generateSheetNetworkId());
        sheetModules.put("信访工单", IdUtils.generateSheetLettersId());
        sheetModules.put("工单流程", IdUtils.generateSheetProcessId());
        sheetModules.put("工单附件", IdUtils.generateSheetAttachmentId());
        
        // 网关模块
        Map<String, Object> gatewayModules = new HashMap<>();
        gatewayModules.put("网关认证", IdUtils.generateGatewayAuthId());
        
        // 开放接口模块
        Map<String, Object> openModules = new HashMap<>();
        openModules.put("开放接口", IdUtils.generateOpenApiId());
        
        result.put("systemModules", systemModules);
        result.put("sheetModules", sheetModules);
        result.put("gatewayModules", gatewayModules);
        result.put("openModules", openModules);
        
        return CommonResult.OK(result);
    }
}
